package net.ming616.nlp.base.dao.impl;

import java.io.Serializable;
import java.util.List;

import net.ming616.nlp.base.dao.GenericTreeDao;
import net.ming616.nlp.base.model.BaseTreeModel;

/**
 * This class serves as the Base class for all other DAOs - namely to hold
 * common CRUD methods that they might all use. You should only need to extend
 * this class when your require custom CRUD logic.
 * <p/>
 * <p>
 * To register this class in your Spring context file, use the following XML.
 * 
 * <pre>
 *      &lt;bean id="fooDao" class="org.appfuse.dao.hibernate.GenericDaoHibernate"&gt;
 *          &lt;constructor-arg value="org.appfuse.model.Foo"/&gt;
 *      &lt;/bean&gt;
 * </pre>
 * 
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a>
 * @param <T>
 *            a type variable
 * @param <PK>
 *            the primary key for that type
 */
@SuppressWarnings("unchecked")
public class GenericTreeDaoImpl<T extends BaseTreeModel<?>, PK extends Serializable>
		extends GenericDaoImpl<T, PK> implements GenericTreeDao<T, PK> {

	public GenericTreeDaoImpl(Class<T> persistentClass) {
		super(persistentClass);
	}

	@Override
	public T save(T object) {
		T parent = (T) object.getParent();
		if (null != parent) {
			object.setLevel(parent.getLevel() + 1);
			if (parent.isLeaf()) {
				parent.setLeaf(false);
				super.save(parent);
			}
		}
		return super.save(object);
	}

	public List<T> getAllLeaves() {
		List<T> list = this.getHibernateTemplate().find(
				" from " + this.persistentClass.getName()
						+ " where leaf is true");
		return list;
	}

}
